# Set working directory and log file
setwd("/Users/fredsolt/Documents/Projects/Religiosity/ Chapter")

# Include required packages
library(foreign)

# Enter data
trend2 <- read.dta("trend2.dta", convert.factors=FALSE, convert.underscore=FALSE) 

# Generate within-country loess predictions
for (c in 1:max(trend2$cc)) {
	cat("Loess for country ",c, "\n", sep="")						# Provide progess report
	c.data <- subset(trend2, cc==c)
	attach(c.data)

	l <- loess(church2 ~ year, model=TRUE)
	p.l <- predict(l, newdata=c.data, se=TRUE)
	
	c.data <- cbind(c.data, p.l$fit, p.l$se.fit)
	if (c==1) trend3 <- c.data else trend3 <- rbind(trend3, c.data)
	detach(c.data)
	rm(c.data)
}

write.table(trend3, file="trend3.csv", sep=",", row.names=TRUE, col.names=NA, na="")
q()

